<template>
  <div id="userCentre">
    <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
      <!--      更新头像-->
      <div class="avatar-container">
        <a-upload
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :custom-request="uploadAvator"
        >
          <a-image v-if="formState.userAvatar" :src="formState.userAvatar" :width="100" :preview="false"/>
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </div>
      <div style="text-align: center; margin-bottom: 5px">头像</div>
      <a-form-item label="用户昵称">
        <a-input v-model:value="formState.userName" />
      </a-form-item>
      <a-form-item label="用户简介">
        <a-textarea v-model:value="formState.userProfile" placeholder="用户简介" :rows="4" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 14, offset: 6 }" style="text-align: center">
        <a-button type="primary" @click="onSubmit" style="width: 100%">修改</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import type { UnwrapRef } from 'vue'
import { reactive, ref } from 'vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { updateUserUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import { testUploadFileUsingPost } from '@/api/fileController.ts'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'

const loginUserStore = useLoginUserStore()
const loginUser = loginUserStore.loginUser
// const imageUrl = ref<string>('')
const loading = ref<boolean>(false)
const formState: UnwrapRef<API.UserUpdateRequest> = reactive({
  id: loginUser.id,
  userName: loginUser.userName,
  userProfile: loginUser.userProfile,
  userAvatar: loginUser.userAvatar,
})
const onSubmit = async () => {
  const res = await updateUserUsingPost(formState)
  if (res.data.code === 0 && res.data.data) {
    message.success('修改成功')
    await loginUserStore.getLoginUser()
  } else {
    message.error('修改失败,' + res.data.message)
  }
}
const uploadAvator = async ({ file }: any) => {
  const res = await testUploadFileUsingPost({}, file)
  if (res.data.code === 0 && res.data.data) {
    formState.userAvatar = res.data.data
    message.success('上传成功')
  } else {
    message.error('上传失败,' + res.data.message)
  }
}
const labelCol = { style: { width: '150px' } }
const wrapperCol = { span: 14 }
// 获取之前的头像
if (loginUser.userAvatar) {
  formState.userAvatar = loginUser.userAvatar
}
</script>

<style scoped>
#userCentre {
  max-width: 500px;
  margin: 0 auto;
}

.avatar-container {
  text-align: center; /* 水平居中 */
  margin-bottom: 5px;
}

.avatar {
  display: inline-block; /* 确保头像作为内联块级元素 */
}
</style>
